feat(x402): production-grade HTTP payment rails, persistent stores, w… - #480
feat(x402): production-grade HTTP payment rails, persistent stores, w…#480Unclebaffa wants to merge 4 commits into
Conversation
…ebhooks, multi-chain quotes, recurring billing, and npm SDK
…debounced call flushing, and Stellar payment verification
…ck, numeric IP SSRF guard, durable counter saving, timing-safe auth comparison, and update package-lock.json
… redirect manual on webhook fetch
Code Review ✅ Approved 11 resolved / 11 findingsProduction-grade HTTP payment infrastructure with multi-chain quotes, persistent stores, and developer SDK, addressing webhook authentication flaws, Stellar verification gaps, SSRF vulnerabilities, and concurrency issues. ✅ 11 resolved✅ Security: Unauthenticated webhook endpoint enables SSRF and fake payment events
✅ Bug: Subscription store write is not concurrency-safe (lost updates/corruption)
✅ Performance: Full-file subscription rewrite on every metered request
✅ Security: SDK gate authorizes Stellar payments without on-chain verification
✅ Security: Webhook auth bypass via Host header when no admin secret set
...and 6 more resolved from earlier reviews OptionsAuto-apply is off → Gitar will not commit updates to this branch. Comment with these commands to change the behavior for this request:
Was this helpful? React with 👍 / 👎 | Gitar |
|
|
@leocagli Please review and merge |



[EPIC] x402 Payment Rails — production-grade HTTP payment gate
Executive Summary
This PR evolves the initial in-memory x402 prototype into a production-grade payment infrastructure for Open Stellar. It delivers persistent receipt and subscription storage, automated settlement webhooks with multi-layered SSRF protection, multi-chain settlement quotes (Stellar XLM, Base ETH, BNB Chain), on-chain transaction verification, recurring billing with monthly usage caps, a 5-line developer SDK (
@open-stellar/x402), and public APIs backing the x402 service catalog marketplace and payment explorer.Implemented Sub-Issues & Feature Checklist
.data/x402-receipts.json) using process-PID swap files.redirect: 'manual'SSRF isolation.@open-stellar/x402): Workspace package exportingwithX402()higher-order route wrapper for gating Next.js App Router API routes in 5 lines.GET /api/protocol/x402/servicesendpoint serving registered API services with pricing, uptime, and reputation metadata./explorerUI &GET /api/explorer/receiptsendpoint for querying and filtering receipts by agent, service, or chain.Technical Architecture & Core Subsystems
1. Persistent Storage Infrastructure
lib/protocols/x402-receipt-store.ts): Durably persists payment receipts to.data/x402-receipts.json. Writes use process PID + timestamp temporary files (${DB_PATH}.${process.pid}.${timestamp}.tmp) swapped atomically to prevent file corruption during server restarts.lib/protocols/x402-subscription-store.ts): Stores active subscriptions, monthly usage counters (callsUsed), statuses (active,grace,paused), and billing event histories in.data/x402-subscriptions.json. IncludesserializeWriteasync mutex queues and synchronous durable updates (saveX402SubscriptionStoreRecordSync) to prevent call-counter loss on serverless cold starts.2. On-Chain Stellar Horizon Verification
lib/protocols/x402.ts):verifyStellarPayment()queries Stellar Horizon API endpoints (https://horizon.stellar.org/transactions/:hash/operations) and verifies transaction success before accepting quotes.payment&create_accountSchema Mapping: Correctly maps both standard XLM native transfers (to,from,amount,asset_type === 'native') and new account activations (account,funder,starting_balance). Enforces mandatory recipient, sender, and minimum XLM amount matching (op.amount >= expectedAmountXlm), rejecting underpayments or dust attacks.3. Webhook Delivery & Multi-Layered SSRF Guard
lib/protocols/x402-webhooks.ts):dispatchX402SettlementWebhook()posts JSON payloads ({ event: 'x402.settlement', timestamp, receipt }) upon settlement.isPrivateOrLoopbackHost()parses hostnames, decimal IPv4 integers (e.g.2130706433), and IPv4-mapped IPv6 (::ffff:169.254.169.254), rejecting loopback (127.0.0.0/8), private subnets (10.0.0.0/8,172.16.0.0/12,192.168.0.0/16), link-local/cloud metadata (169.254.0.0/16),.internal, and.localtargets.sendWebhookHttpRequest()setsredirect: 'manual'onfetch()calls and rejects 30x HTTP redirects, preventing attackers from bypassing initial domain checks via HTTP redirects.4. Authentication & Fail-Closed Security
app/api/protocol/x402/webhooks/route.ts):isAuthorized()fails closed in production whenever no admin secret is configured.crypto.timingSafeEqualwith length-matched byte buffers (safeCompare()) to eliminate timing side-channel attacks onAuthorization: BearerandX-Admin-Secretheaders.5. Developer SDK (
@open-stellar/x402)packages/x402and wrapperlib/sdk/x402-sdk.tsenable route gating in 5 lines:File Changes Matrix
lib/protocols/x402.tslib/protocols/x402-subscription-store.tslib/protocols/x402-receipt-store.tslib/protocols/x402-webhooks.tsredirect: 'manual'fetchlib/sdk/x402-sdk.ts@open-stellar/x402SDK route gating wrapper (withX402)app/api/protocol/x402/webhooks/route.tsapp/api/protocol/x402/services/route.tsapp/api/protocol/x402/subscriptions/renew/route.tspackages/x402/package.json@open-stellar/x402workspace SDK package manifestpackage-lock.json__tests__/x402-ssrf-guard.test.ts__tests__/x402-stellar-verification.test.tspayment&create_accounton-chain verification__tests__/x402-subscription-concurrency.test.ts__tests__/x402-subscriptions-persistence.test.ts__tests__/x402-webhooks.test.tsSecurity Audit & Hardening Matrix
fetch()isPrivateOrLoopbackHost()blocks RFC1918,127.0.0.0/8, link-local/cloud metadata169.254.169.254, and numeric/IPv6 encodings.fetch()defaulted toredirect: 'follow'redirect: 'manual'onfetch()calls and reject 30x HTTP redirect responses.Hostheader check when secret unconfiguredisAuthorized()fails closed in production if no secret is set, ignoringHostheaders.===comparisonsafeCompare()usingcrypto.timingSafeEqualwith length-checked byte buffers.verifyX402SettlementpassesexpectedAmountXlmandverifyStellarPaymentrejects operations whereop.amount < expectedAmountXlm.create_accountVerification Bypasscreate_accountops use different Horizon field namesaccount,funder, andstarting_balancefields forcreate_accountoperations and required mandatory field matches.serializeWrite) and PID-tagged.tmpswap files.saveX402SubscriptionStoreRecordSync).Verification & CI Testing
npx tsc --noEmit # Exit code 0 (0 errors)Updated
package-lock.jsonwith workspace package registry entry@open-stellar/x402to ensurenpm cisucceeds in GitHub Actions Playwright E2E workflows.Closes #18